import axios from 'axios';
import router from './router';

import {
    Loading,
    Message
} from 'element-ui';

let loading;
function startLoad() {
    loading = Loading.service({
        lock: true,
        text: '拼命加载中。。。',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function endLoad() {
    loading.close();
}

//请求拦截
axios.interceptors.request.use(config => {
    startLoad();
    if(localStorage.eleToken){
         //设施统一的请求token    
        config.headers.Authorization = localStorage.eleToken;
    }
    return config;
}, error => {
    return Promise.reject(error);
})

//响应拦截
axios.interceptors.response.use(response => {
    endLoad();

    return response;
}, error => {
    //错误提醒
    endLoad();
    console.log("请求结束",error.response)
    //判断token是否失效
    const {status} = error.response;
    if(status == 401){
        Message.error("token失效，请重新登录")
        //清除token
        localStorage.removeItem('eleToken');
        //跳转登录页
        router.push('/login');
    }
    return Promise.reject(error);
})


export default axios